package com.jzy.hzit.handler;

import com.jzy.hzit.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Configuration
@Slf4j
public class GatewayExceptionHandler implements WebExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        String errorMessage;

        if (ex instanceof NotFoundException) {
            errorMessage = "服务未找到";
        } else if (ex instanceof ResponseStatusException) {
            errorMessage = ex.getMessage();
        } else {
            errorMessage = "内部服务器错误";
        }

        log.error("[网关异常处理] 请求路径: {}, 异常信息: {}", exchange.getRequest().getPath(), ex.getMessage());

        return ResponseUtil.writeToResponse(response, errorMessage);
    }
}

class ResponseUtil {
    public static Mono<Void> writeToResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(getStatusForMessage(message));
        response.getHeaders().add("Content-Type", "application/json");
        return response.writeWith(Mono.just(response.bufferFactory().wrap(message.getBytes())));
    }

    private static org.springframework.http.HttpStatus getStatusForMessage(String message) {
        if (message.contains("服务未找到")) {
            return org.springframework.http.HttpStatus.NOT_FOUND;
        } else if (message.contains("内部服务器错误")) {
            return org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
    }
}
